package datalookin.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import datalookin.adapter.ChooseStationAdapter;
import datalookin.adapter.ChooseTypeAdapter;
import datalookin.adapter.HistoryAdapter;
import datalookin.dto.StationDataDto;
import inter.Delegate;
import model.Commontype;
import model.Stationnumposition;
import datalookin.network.GetHistoryWaterInfo;
import utils.CacheHelper;
import utils.TimeUtil;

/**
 * 历史数据
 * Created by Administrator on 2016/3/5.
 */
public class GuanWangHistoryActivity extends UIHandler.BaseActivity {

    private Button btn_back;
    Spinner spinner_loc;
    ChooseStationAdapter chooseStationAdapter;
    List<Stationnumposition> stations = new ArrayList<Stationnumposition>();

    Spinner spinner_type;
//    List<String> typeArray = new ArrayList<String>();
    List<Commontype> typeArray = new ArrayList<Commontype>();
    ChooseTypeAdapter chooseTypeAdapter;

    Button btn_timeStart;
    Button btn_timeStop;

    GetHistoryWaterInfo getHistoryWaterInfo;

    Calendar calendar = Calendar.getInstance();
    String timeStart = TimeUtil.currentDate();
    String timeEnd = timeStart;
    int start_year=calendar.get(Calendar.YEAR),start_month=calendar.get(Calendar.MONTH),start_day=calendar.get(Calendar.DAY_OF_MONTH);
    int end_year = start_year,end_month = start_month,end_day = start_day;

    String selectId;
    String selectType;

    ListView lv_history;
    List<StationDataDto> history_items = new ArrayList<StationDataDto>();
    HistoryAdapter historyAdapter = new HistoryAdapter();

    Delegate historyImp = new Delegate() {
        @Override
        public void onResponse(String response) {
            Log.i("历史数据", response);
            List<StationDataDto> tmp = JSON.parseArray(response,StationDataDto.class);
            history_items.clear();
            if (tmp != null)
                history_items.addAll(tmp);
            historyAdapter.notifyDataSetChanged();

        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(GuanWangHistoryActivity.this,"历史数据下载失败",Toast.LENGTH_SHORT).show();
        }
    };


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_timeStart) {
                // 日期选择器
                Calendar calendar = Calendar.getInstance();
                Dialog dialog;
                dialog = new DatePickerDialog(GuanWangHistoryActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String tmpDate = year+"/"+(((monthOfYear+1)<=9&&(monthOfYear+1)>=1)?"0"+(monthOfYear+1):(1+monthOfYear)+"")+"/"+((dayOfMonth>=1&&dayOfMonth<=9)?"0"+dayOfMonth:dayOfMonth+"");
                        timeStart = tmpDate;
                        start_year = year;
                        start_month = monthOfYear;
                        start_day = dayOfMonth;
                        btn_timeStart.setText(start_year+"年"+(start_month+1)+"月"+start_day+"日");
                        getHistoryInfo();
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            } else if (v == btn_timeStop) {
                // 日期选择器
                Calendar calendar = Calendar.getInstance();
                Dialog dialog;
                dialog = new DatePickerDialog(GuanWangHistoryActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String tmpDate = year+"/"+(((monthOfYear+1)<=9&&(monthOfYear+1)>=1)?"0"+(monthOfYear+1):(monthOfYear+1)+"")+"/"+((dayOfMonth>=1&&dayOfMonth<=9)?"0"+dayOfMonth:dayOfMonth+"");
                        timeEnd = tmpDate;
                        end_year = year;
                        end_month = monthOfYear;
                        end_day = dayOfMonth;
                        btn_timeStop.setText(end_year+"年"+(end_month+1)+"月"+end_day+"日");
                        if (timeEnd.compareTo(timeStart)<=0)
                        {
                            Toast.makeText(GuanWangHistoryActivity.this,"结束时间应大于起始时间",Toast.LENGTH_SHORT).show();
                        }
                        getHistoryInfo();
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            }
            else if (v == btn_back)
            {
                GuanWangHistoryActivity.this.finish();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        initview();
        initdata();
    }

    private void initdata() {
        CacheHelper preferenceHelper = new CacheHelper(GuanWangHistoryActivity.this);
        if (preferenceHelper.contains(CacheHelper.PLANTSTATIONS, "data")) {
            String str = preferenceHelper.getString(CacheHelper.PLANTSTATIONS, "data");
            List<Stationnumposition> stationsTmp = JSON.parseArray(str, Stationnumposition.class);
            stations.addAll(stationsTmp);
            chooseStationAdapter.notifyDataSetChanged();
        }

        if (preferenceHelper.contains(CacheHelper.COMMENTTYPE,"data"))
        {
            String str = preferenceHelper.getString(CacheHelper.COMMENTTYPE,"data");
            List<Commontype> commontypes = JSON.parseArray(str,Commontype.class);
            typeArray.addAll(commontypes);
            chooseTypeAdapter.notifyDataSetChanged();
        }

    }

    // 初始化界面
    private void initview() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(onClickListener);

        spinner_loc = (Spinner) findViewById(R.id.id_spinner_loc);
        chooseStationAdapter = new ChooseStationAdapter();
        chooseStationAdapter.setStations(stations);
        spinner_loc.setAdapter(chooseStationAdapter);
        spinner_loc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Stationnumposition stationnumposition = stations.get(position);
                selectId = stationnumposition.getStationnum();
                getHistoryInfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinner_type = (Spinner) findViewById(R.id.id_spinner_type);
        chooseTypeAdapter = new ChooseTypeAdapter();
        chooseTypeAdapter.setTypeArray(typeArray);
        spinner_type.setAdapter(chooseTypeAdapter);
        spinner_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectType = typeArray.get(position).getType();
                getHistoryInfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        btn_timeStart = (Button) findViewById(R.id.id_btn_timeBegin);
        btn_timeStart.setText(start_year + "年" + (start_month + 1) + "月" + start_day + "日");
        btn_timeStart.setOnClickListener(onClickListener);

        btn_timeStop = (Button) findViewById(R.id.id_btn_timeStop);
        btn_timeStop.setText(end_year+"年"+(end_month+1)+"月"+end_day+"日");
        btn_timeStop.setOnClickListener(onClickListener);

        lv_history = (ListView) findViewById(R.id.id_lv_history);
        lv_history.setEmptyView(findViewById(R.id.id_v_nonemsg));
        historyAdapter.setHistory_items(history_items);
        lv_history.setAdapter(historyAdapter);

    }

    /**
     * 获取历史数据
     */
    public void getHistoryInfo()
    {
        if (timeEnd == null || timeStart == null || selectType == null || selectId == null)return;
        getHistoryWaterInfo = new GetHistoryWaterInfo(timeStart,historyImp,timeEnd,selectId,selectType);
        try {
            getHistoryWaterInfo.get();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(getHistoryWaterInfo != null)
            getHistoryWaterInfo.cancel();
    }
}
